<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Knowledge Base Chat</title>
    <script type="text/javascript">
        function sendMessage() {
            var queryInput = document.getElementById("query-input").value;
            var messageData = {
                'query': queryInput,
                'knowledge_base_name': 'zszt1',
                'top_k': 3,
                'score_threshold': 1,
                'history': [
                    {'role': 'user', 'content': '你好'},
                    {'role': 'assistant', 'content': '你好，我是 ChatGLM'}
                ],
                'stream': true
            };

            fetch('/send_message', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(messageData)
            })
            .then(response => {
                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                
                let eventsDiv = document.getElementById("events");

                // Read the data
                function processText({ done, value }) {
                    if (done) {
                        console.log("Stream complete");
                        return;
                    }

                    // Decode and add the chunk of data directly as a string
                    let chunk = decoder.decode(value, { stream: true });
                    console.log(chunk)
                    eventsDiv.innerHTML += "<p>" + chunk + "</p>";

                    // Read the next chunk of data
                    reader.read().then(processText);
                }

                // Start reading the stream
                reader.read().then(processText);
            })
            .catch((error) => {
                console.error('Error:', error);
            });
        }
    </script>
</head>
<body>
    <h1>Knowledge Base Chat</h1>
    <input type="text" id="query-input" placeholder="请输入查询...">
    <button onclick="sendMessage()">发送</button>
    <div id="events"></div>
</body>
</html>
